package com.example.reggie.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.reggie.common.R;
import com.example.reggie.entity.Employee;
import com.example.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/employee")

public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    /**
     * 员工登录
     * @param request
     * @param employee
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
        // 1.获取密码进行加密
        String password=employee.getPassword();
        password=DigestUtils.md5DigestAsHex(password.getBytes());
        // 2.查询数据库中是否有这个用户
        LambdaQueryWrapper<Employee>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee ee=employeeService.getOne(queryWrapper);
        if (ee==null){
            return R.error("登陆失败,用户名不存在");
        }
        // 3.比较密码是否匹配
        System.err.println("数据库密码："+ee.getPassword());
        System.err.println("输入的密码："+password);
        if (!(ee.getPassword().equals(password))){
            return R.error("密码错误");
        }
        // 4.查看用户状态是否为封禁状态
        if (ee.getStatus().equals(0)){
            return R.error("用户被封禁");
        }
        // 5.登陆成功,设置session
        request.getSession().setAttribute("employeeId",ee.getId());
        System.err.println("session: employeeId数据存放是否成功:"+request.getSession().getAttribute("employeeId"));
        return R.success(ee);
    }

    /**
     * 员工退出
     * @param request
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        // 1.清理session
        request.getSession().removeAttribute("employeeId");
        // 2.退出
        return R.success("退出成功");
    }

    /**
     * 新增员工
     * @param request
     * @param employee
     */
    @PostMapping()
    public R<String> save(HttpServletRequest request,@RequestBody Employee employee){
        // 1.设置初始密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        // 2.设置创建和更新的时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        // 3.设置操作者
        Long eid = (Long) request.getSession().getAttribute("employeeId");
        System.err.println("操作者Id:"+eid);
//        employee.setCreateUser(eid);
//        employee.setUpdateUser(eid);
        System.out.println("待插入的对象:"+employee);
        // 4.存储到数据库
        boolean save=true;
        //捕获用户已经存在的异常
        save = employeeService.save(employee);
        if (!save){
            return R.error("数据插入失败");
        }
        return R.success("插入成功");
    }


    /**
     * 查询所有员工并模糊
     * @param page
     * @param pageSize
     * @param name
     */
    @GetMapping("/page")
    public R<IPage> page(int page, int pageSize, String name){
        log.info("page:{} pageSize:{} name:{}",page,pageSize,name);

        IPage page1 =new com.baomidou.mybatisplus.extension.plugins.pagination.Page(page,pageSize);

        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<>();
        //模糊查询(如果有)
        queryWrapper.like(!StringUtils.isEmpty(name),Employee::getName,name);
        //降序排序
        queryWrapper.orderByDesc(Employee::getUpdateTime);

        employeeService.page(page1,queryWrapper);
        return R.success(page1);
    }

    /**
     * 查询一个员工
     * @param
     */
    @GetMapping("/{id}")
    public R<Employee> get(@PathVariable Long id){
        // 1.条件设置 id
        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getId,id);
        // 2.查询
        Employee employee=employeeService.getOne(queryWrapper);
        if (employee==null){
            return R.error("错误");
        }
        // 3.回显
        return R.success(employee);
    }

    /**
     * 修改员工
     * @param request
     * @param employee
     */
    @PutMapping()
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee){
        // 1.获取修改者的id
        Long id=(Long)request.getSession().getAttribute("employeeId");
        // 2.设置
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(id);
        // 3.MP修改
        boolean flage = employeeService.updateById(employee);
        if (!flage) {
            return R.error("修改失败");
        }
        return R.success("修改成功");
    }





}
